<?php

namespace app\admin\service;

use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use app\admin\model\System;
use Darabonba\OpenApi\Models\Config;

class Aliphone
{

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient($accessKeyId, $accessKeySecret)
    {
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    public static function sendPhone($phone = null, $code = null)
    {
        if (empty($phone) || empty($code)) {
            return json_encode(array("code"=>400,"data"=>"参数不完整"));
        }
        //获取验证码的信息
        $model = new System();
        $value = $model->getValueBytype('phone');
        //把验证码 转换为json
        $TemplateParam = json_encode(array($value["TemplateParam"] => $code));
        $client = self::createClient($value["accessKeyId"], $value["accessKeySecret"]);
        $sendSmsRequest = new SendSmsRequest([
            "signName" => $value["SignName"],
            "templateCode" => $value["TemplateCode"],
            "phoneNumbers" => $phone,
            "templateParam" => $TemplateParam
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $res = $client->sendSmsWithOptions($sendSmsRequest,$runtime);
            return json_encode(array("code"=>200,"data"=>$res));
        } catch (ServerException $e) {
            return json_encode(array("code"=>400,"data"=>$e));
        }
    }
}
